import { h } from "koishi"

export const name = "poke"

export function apply(ctx) {
  ctx = ctx.platform("onebot")

  const pokeTimesMap = new Map()

  ctx.on("notice", async session => {
    if (session.event.subtype !== "poke") return
    if (session.userId === session.selfId || session.guildId && session.targetId !== session.selfId && (!pokeTimesMap.has(session.cid) || session.targetId !== session.userId)) return
    if ((await session.observeChannel(["assignee"])).assignee !== session.selfId) return

    let times = (pokeTimesMap.get(session.cid) ?? 0) + 1
    ctx.logger.debug(times)
    if (Number.isNaN(times)) return
    pokeTimesMap.set(session.cid, NaN)
    await ctx.sleep(2000 + 2000 * Math.random())
    if (!pokeTimesMap.has(session.cid)) times = 0
    pokeTimesMap.set(session.cid, times)

    // 戳自己目前只在群内有效
    const pokeSelfProb = times > /*6*/2 ? 0.4 - 1 / (times - 3.5) : 0
    //const pokeOtherProb = times > 2 ? 0.8 - 1 / (times - 0.75) : 0
    const rand = Math.random()

    if (rand < pokeSelfProb) poke(session, session.selfId)
    else /*if (rand < pokeOtherProb)*/ poke(session, session.userId)
  })

  ctx.middleware(async (session, next) => {
    pokeTimesMap.delete(session.cid)
    return next()
  })

  function poke(session, userId) {
    if (session.isDirect) session.onebot._request("friend_poke", { user_id: session.userId })
    else session.onebot._request("group_poke", { group_id: session.channelId, user_id: userId })
  }
}
